<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/phorm/forms/validators/Validator.php';

class Form
{
	public $isValid;
	public $formData;
	public $validators;
	public $fileData;
	
	protected $delegate;
	
	public static function formWithKeyAndDelegate($key, IFormDelegate &$delegate)
	{
		$form = new Form($key);
		$form->setDelegate($delegate);
		$form->process();
		return $form;
	}
	
	public function __construct($key='default')
	{
		$this->validators = array();
		$this->class      = $formDataKey;
		
		if (isset($_POST[$key]))
		{
			$this->formData =& $_POST[$key];
		}
		else
		{
			$this->formData =& $_POST;
		}
		
		if(count($_FILES)){
			$this->fileData = $_FILES;
		}
	}
	
	public function setDelegate(IFormDelegate &$delegate)
	{
		$this->delegate = $delegate;
	}
	
	public function delegate()
	{
		return $this->delegate;
	}
	
	public function addValidator(Validator $validator)
	{
		array_push($this->validators, $validator);
	}
	
	public function process()
	{
		if($this->delegate)
			$this->delegate->willProcessForm($this);
			
		if(count($this->validators))
			$this->validateForm();
		else
			$this->isValid = true;
		
		if($this->delegate)
			$this->delegate->didProcessForm($this);
		
	}
	
	public function getFiles($value)
	{
		
	}
	
	public function __get($value)
	{
		if(isset($this->formData) && array_key_exists($value, $this->formData))
		{
			return $this->formData[$value];
		}
		else if(isset($this->fileData) && array_key_exists($value, $this->fileData))
		{
			return $this->fileData[$value]['name'];
		}
		
	}
	
	protected function validateForm()
	{
		$length  = count($this->validators);
		$tmpFlag = true;
		
		for($i = 0; $i < $length; $i++ )
		{
			$currentValidator =& $this->validators[$i];
			$currentValidator->validate();
			
			if($currentValidator->isRequired)
				$tmpFlag = ($tmpFlag && $currentValidator->isValid);
		}
		
		if($tmpFlag != $this->isValid)
			$this->isValid = $tmpFlag;
		
		if($this->isValid)
			$this->formWillSucceed();
		else
			$this->formWillFail();
	}
	
	protected function formWillSucceed() { }
	protected function formWillFail()
	{
		$this->willClearInvalidValues();
	}
	
	
	
	protected function willClearInvalidValues()
	{
		foreach($this->validators as $value)
		{
			if(!$value->isValid)
			{
				if($value->keys)
				{
					foreach($value->keys as $key)
						unset($this->formData[$key]);
				}
				else
				{
					unset($this->formData[$value->key]);
				}
				
			}
		}
	}
}

?>